<?php
namespace app\common\lib\model_operate\query;

use app\common\lib\model_operate\QueryDevice;
use app\common\lib\model_operate\Tools;
use think\Db;

/**
 *单表查询
 */
class Single extends QueryDevice
{
    private $flags = ['Db', 'Model'];
    private $config; //所有配置
    private $baseInfo; //主表基础信息

    public function __construct($config)
    {
        if (!empty($config)) {
            $this->config   = $config;
            $this->baseInfo = $config->getBase();
        }
    }

    /**
     * 查询
     */
    public function toQuery()
    {
        $type = "executeDb";
        if (method_exists($this, $type)) {
            return $this->$type();
        }
        return null;
    }

    /**
     * 执行Db查询
     */
    public function executeDb()
    {

        $obj = Db(Tools::tableNameFormat($this->baseInfo['tableName']));
        return $this->condition($obj);
    }

    /**
     * 执行Model查询
     */
    public function executeModel()
    {
        $obj = Tools::tableToModel($this->baseInfo['tableName']);
        return $this->condition($obj);
    }

    /**
     * 条件
     */
    private function condition($obj)
    {
        $this->setKey(); //设置主键显示
        //查询条件
        $where = $this->config->getWhere();
        if (!empty($where)) {
            $obj = $obj->where($where);
        }
        //字段筛选
        $fields = [];
        foreach ($this->baseInfo['displayFields'] as $key => $value) {
            $str      = ($value != $key) ? ($key . " as " . $value) : $key;
            $fields[] = $str;
        }
        if (!empty($fields)) {
            $obj = $obj->field(implode(',', $fields));
        }
        return $obj;
    }

    /**
     * 主表主键显示设置
     */
    private function setKey()
    {
        $key = $this->baseInfo['tableInfo']['pk'];
        if (!empty($this->baseInfo['displayFields']) && !in_array($key, array_keys($this->baseInfo['displayFields']))) {
            $this->baseInfo['displayFields'][$key] = $key;
        }
    }

    public function getFlags()
    {
        return $this->flags;
    }

}
